<template>
  <div>
    <a-card>
      <a-descriptions title="当前工单" bordered size="small">
        <a-descriptions-item label="报修单id">{{
          ticketForm.id
        }}</a-descriptions-item>
        <a-descriptions-item v-if="ticketForm.repair" label="工单号">{{
          ticketForm.repair.order_no
        }}</a-descriptions-item>
        <a-descriptions-item label="维修方式" v-if="ticketForm.repair">{{
          ticketForm.repair.way == 1 ? "门店" : "现场应急"
        }}</a-descriptions-item>
        <a-descriptions-item label="车位" v-if="ticketForm.parking"
          >{{ ticketForm.parking.parking_type
          }}{{ ticketForm.parking.no }}</a-descriptions-item
        >
        <a-descriptions-item label="车型" v-if="ticketForm.kind">{{
          ticketForm.kind.union_name
        }}</a-descriptions-item>
        <a-descriptions-item label="工单类型">{{
          ticketForm.ticket_type == 1 ? "正常" : "异常"
        }}</a-descriptions-item>

        <a-descriptions-item label="状态">
          <a-badge
            status="processing"
            :text="ticketForm.state == 1 ? '进行中' : '已完结'"
          />
        </a-descriptions-item>
        <a-descriptions-item label="维修工" :span="6">
          {{ ticketForm.users.map((item) => item.name).toString(",") }}
        </a-descriptions-item>
        <a-descriptions-item label="服务项目" :span="12">
          <div v-for="(s, index) in ticketForm.services" :key="index">
            {{ s.name }}
            <br />
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="目前工时" :span="12">
          {{ manhoursCount }}
        </a-descriptions-item>
      </a-descriptions>

      <div class="mt-6">
        <p class="text-xl font-bold mb-4 text-center">工单修改</p>
        <a-form
          ref="formRef"
          :model="formState"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 8 }"
          class="border border-gray-200 solid"
        >
          <a-form-item
            label="报修单id"
            name="id"
            :rules="[
              ruleStore.getRule('id')
                ? ruleStore.getRule('id')
                : { required: false },
            ]"
          >
            <a-input v-model:value="formState.id" disabled></a-input>
          </a-form-item>

          <a-form-item
            label="新增服务"
            name="services_id"
            :rules="[
              ruleStore.getRule('services_id')
                ? ruleStore.getRule('services_id')
                : { required: false },
            ]"
          >
            <a-select
              v-model:value="formState.service_ids"
              mode="multiple"
              placeholder="选择项目"
              style="width: 100%"
              show-search
              :default-active-first-option="false"
              :not-found-content="null"
              :filter-option="false"
              :options="options.servicesOptions"
              @search="handleServiceSearch"
            >
            </a-select>
          </a-form-item>

          <a-form-item
            label="新增维修工"
            name="user_ids"
            :rules="[
              ruleStore.getRule('user_ids')
                ? ruleStore.getRule('user_ids')
                : { required: false },
            ]"
          >
            <a-select
              v-model:value="formState.user_ids"
              mode="multiple"
              placeholder="选择维修工"
              style="width: 100%"
              @change="changeUser"
              :default-active-first-option="false"
              :not-found-content="null"
              :options="options.userOptions"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="工时管理">
            <a-radio-group v-model:value="formState.hand" name="radioGroup">
              <a-radio value="1">系统</a-radio>
              <a-radio value="2">手工</a-radio>
            </a-radio-group>
            <a-form-item-rest v-if="formState.hand == '2'">
              <div class="mt-3">
                <div class="flex justify-start items-center">
                  <div class="text-red-500 mr-3">额外工时</div>
                  <a-input-number
                    id="inputNumber"
                    size="large"
                    step="0.5"
                    v-model:value="addScore"
                    :min="0.5"
                    :max="10"
                  />
                </div>
                <p class="text-red-500 text-lg">
                  改后工时【{{ addScore + manhoursCount }}】
                </p>
              </div>

              <div class="mt-3">
                分配工时
                <span
                  :class="
                    formState.score_assigns.reduce(
                      (acc, curr) => acc + curr.score,
                      0
                    ) ==
                    addScore + manhoursCount
                      ? 'isOk'
                      : ''
                  "
                >
                  {{
                    formState.score_assigns.reduce(
                      (acc, curr) => acc + curr.score,
                      0
                    )
                  }}
                </span>
                <table>
                  <thead>
                    <tr>
                      <th scope="col">姓名</th>
                      <th scope="col">工时</th>
                      <th scope="col">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(u, index) in addUserOpts" :key="index">
                      <th scope="row">{{ u.label }}</th>
                      <td>
                        <a-input-number
                          id="inputNumber"
                          step="0.5"
                          size="large"
                          style="width: 200px"
                          :min="0.5"
                          v-model:value="
                            formState.score_assigns[index]['score']
                          "
                        />
                      </td>
                      <td>
                        <a-button
                          type="primary"
                          danger
                          @click="deleteUser(u)"
                          :disabled="
                            ticketForm.users.some((i) => i.id == u.value)
                          "
                          >删除</a-button
                        >
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 8, span: 2 }">
            <a-button type="primary" style="width: 100px" @click="onSubmit"
              >提交</a-button
            >
          </a-form-item>
        </a-form>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import Api from "@/api/backend/api";
import useRuleStore from "@/store/modules/rule";
import { debounce } from "lodash-es";
import { message } from "ant-design-vue";
const route = useRoute();
const router = useRouter();
let id = route.params.id;
const addScore = ref(1);
const ruleStore = useRuleStore();
const manhours = ref({});
const manhoursCount = ref(0);
const getManhours = async () => {
  let service_ids = ticketForm.value.services.map((item) => item.id);
  let data = await Api.manhourController.query({
    service_ids: service_ids,
    kind_id: ticketForm.value.kind_id,
  });
  manhours.value = data;
  manhoursCount.value = manhours.value.reduce(
    (acc, curr) => acc + curr.score,
    0
  );
};

const deleteUser = (row) => {
  console.log(row, addUserOpts.value);
  let ind = addUserOpts.value.findIndex((i) => i.value == row.value);
  addUserOpts.value.splice(ind, 1);
  let index = formState.value.score_assigns.findIndex((i) => i.id == row.value);
  formState.value.score_assigns.splice(index, 1);
};
const getTicket = async () => {
  if (id != null && id != undefined) {
    ticketForm.value = await Api.ticketController.show({
      id: id,
    });
    if (ticketForm.value.services == null) {
      ticketForm.value.services_id = [];
    }
    if (ticketForm.value.users == null) {
      ticketForm.value.user_ids = [];
    }

    console.log(ticketForm.value, 1);
    formState.value.id = ticketForm.value.id;

    // formState.value.user_ids = ticketForm.value.users.map((item) => item.id);
    await getManhours();

    addUserOpts.value = ticketForm.value.users.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    formState.value.id = ticketForm.value.id;
    formState.value.score_assigns = ticketForm.value.users.map((item) => {
      return {
        user_id: item.id,
        score: 0,
      };
    });
  }
};

const addUserOpts = ref([]);

//当改变维修工时
const changeUser = (val) => {
  let opt = options.value.userOptions.filter((item) =>
    val.some((i) => i == item.value)
  );
  addUserOpts.value = [...new Set([...toRaw(addUserOpts.value),...opt])];
  formState.value.score_assigns = addUserOpts.value.map((item) => {
    return {
      user_id: item.value,
      score: 0,
    };
  });
};

const options = ref({
  typeOptions: [],
  userOptions: [],
  servicesOptions: [],
  parkingOptions: [],
});

// 手动提交
const formState = ref({
  id: null,
  user_ids: [],
  service_ids: [],
  hand: "1",
  score_assigns: [],
});

// 数据展示用
const ticketForm = ref({
  id: null,
  repair_id: null,
  kind_id: null,
  repair_way: null,
  parking_id: null,
  ticket_type: 2,
  state: 1,
  users: [],
  services_id: [],
  services: [],
  kind: {},
});

const changeNumber = (val) => {
  console.log(val);
};

const getTypeOption = async () => {
  let data = await Api.kindController.option();
  options.value.typeOptions = data.map((item) => {
    return {
      label: item.union_name,
      value: item.id,
    };
  });
};

const getParkingOption = async () => {
  let data = await Api.parkingController.option();
  options.value.parkingOptions = data.map((item) => {
    return {
      label: `${item.parking_type}${item.no}`,
      value: item.id,
      disabled: true,
    };
  });
};
const getServiceOption = async () => {
  let data = await Api.serviceController.option({
    name: null,
  });
  let opts = data
    .filter((i) => ticketForm.value.services.some((item) => item.id != i.id))
    .map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  console.log(`~~~~~~`, opts);
  options.value.servicesOptions = opts;
};



const getEmployee = async () => {
  options.value.userOptions = [];
  let data = await Api.userController.employeeList();
  options.value.userOptions = data.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
};
getTypeOption();
getParkingOption();

getEmployee();
const handleServiceSearch = debounce(async (value) => {
  console.log("fetching service", value);
  if (value == "") return;

  options.value.servicesOptions = [];
  let data = await Api.serviceController.option({
    name: value,
  });
  let opts = data
    .filter((i) => ticketForm.value.services.every((item) => item.id != i.id))
    .map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  options.value.servicesOptions = opts;
}, 300);

const onSubmit = async () => {
  if (formState.value.hand == "2") {
    let assignScore = formState.value.score_assigns.reduce(
      (acc, curr) => acc + curr.score,
      0
    );
    if (addScore.value + manhoursCount.value != assignScore) {
      return message.error("工时分配错误");
    }
  }

  await Api.ticketController.abNormal(formState.value);
  // await Api.ticketController.abNormal(ticketForm.value);
  // router.go(-1);
};

getTicket();
</script>

<style lang="less" scoped>
table {
  width: 500px;
  border-collapse: collapse;
  border: 2px solid rgb(140 140 140);
  font-family: sans-serif;
  font-size: 0.8rem;
  letter-spacing: 1px;
}

caption {
  caption-side: bottom;
  padding: 10px;
  font-weight: bold;
}

thead,
tfoot {
  background-color: rgb(228 240 245);
}

th,
td {
  border: 1px solid rgb(160 160 160);
  padding: 8px 10px;
}

td:last-of-type {
  text-align: center;
}

tbody > tr:nth-of-type(even) {
  background-color: rgb(237 238 242);
}

tfoot th {
  text-align: right;
}

tfoot td {
  font-weight: bold;
}
.isOk {
  color: green;
  font-size: 24px;
}
</style>
